#include <stdint.h>
extern void printInPos(char *msg, uint16_t, uint8_t row, uint8_t col);
extern void putchar(char c);
extern char getch();

// char tempc

// 字符串长度
uint16_t strlen(char *str)
{
  int count = 0;
  while (str[count++] != '\0')
  {
  }
  return count - 1;
}

// 比较字符串
uint8_t strcmp(char *str1, char *str2)
{
  int i = 0;
  while (1)
  {
    if (str1[i] == '\0' || str2[i] == '\0')
    {
      break;
    }
    if (str1[i] != str2[i])
    {
      break;
    }

    ++i;
  }
  return str1[i] - str2[i];
}

// 在光标显示字符串
void print(char *str)
{
  for (int i = 0, len = strlen(str); i < len; i++)
  {
    putchar(str[i]);
  }
}

void printNum(uint16_t num){
  char numStr[7];
  int i =0;
  int last = 6;
  while(i<= last){
    if(num >9){
      numStr[last - i] = num %10;
      num /=10;
      ++i;
    }else {
      break;
    }
  }
  numStr[i] = '\0';
  print(numStr);
}

void readToBuf(char *buf, uint16_t maxlen)
{
  int i = 0;
  while (1)
  {
    char tempc = getch();
    if (!(tempc == 0xD || tempc == '\b' || tempc >= 32 && tempc <= 127))
    {
      continue;
    }
    if (i > 0 && i < maxlen)
    {
      // 按下回车停止读取
      if (tempc == 0x0D)
      {
        break;
      }
      else if (tempc == '\b')
      {
        putchar('\b');
        putchar(' ');
        putchar('\b');
        --i;
      }
      else
      {
        putchar(tempc);
        buf[i] = tempc;
        ++i;
      }
    }
    else if (i > maxlen - 1)
    {
      if (tempc == '\b')
      {
        putchar('\b');
        putchar(' ');
        putchar('\b');
      }
      else if (tempc == 0x0D)
      {
        break;
      }
    }
    else if (i <= 0)
    {
      if (tempc == 0x0D)
      {
        break;
      }
      else if (tempc != '\b')
      {
        putchar(tempc);
        buf[i] = tempc;
        ++i;
      }
    }
  }
  putchar('\r');
  putchar('\n');
  buf[i] = '\0';
}

// 取得字符串中的第一个单词
void getFirstWord(char *str, char *buf)
{
  int i = 0;
  while (str[i] && str[i] != ' ')
  {
    buf[i] = str[i];
    ++i;
  }
  buf[i] = '\0';
}